package com.manage.utils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 作者：威哥
 * 时间：2021/9/28 15:52
 * 描述：永无bug
 */
public class FileUploadUtils {
    public static String uploadFile(HttpServletRequest request,String name) throws IOException, ServletException {
        //1、获取Part对象
        Part part = request.getPart(name);
        //2、获取文件的保存名称
        //获取文件上传名称
        String oldFilename = part.getSubmittedFileName();
        if(oldFilename == null || "".equals(oldFilename)){
            return null;
        }

        //获取文件后缀
        String fileExt = oldFilename.substring(oldFilename.lastIndexOf("."));
        //使用UUID生成一个随机的文件名
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String fileName = uuid+fileExt;
        //3、确定保存的路径
        File file = new File("F:\\QQrecive\\upload");
        if(!file.exists())
            file.mkdirs();
        //4、将上传的文件保存下来
        part.write(file.getAbsolutePath()+"\\"+fileName);

        return fileName;
    }
}
